﻿using System.Collections.Generic;
using System.Linq;
using PicoContainer;
using XEvolve.Core.Runtime;
using XEvolve.Core.Runtime.Attributes;

namespace XEvolve.Presentation.Input.Internal
{
    internal class AdvisorManager : IStartable
    {
        private readonly IDictionary<string, IList<AdvisorBinding>> advisorBindings = new Dictionary<string, IList<AdvisorBinding>>();
        private readonly IExtensionPoint advisors;

        public AdvisorManager([Extensions("xevolve.presentation.advisor.bindings")]AdvisorBinding[] bindings, [ExtensionPoint("xevolve.presentation.advisors")]IExtensionPoint advisors)
        {
            this.advisors = advisors;
            foreach (var advisorBinding in bindings)
            {
                if (!advisorBindings.ContainsKey(advisorBinding.ElementId))
                {
                    advisorBindings[advisorBinding.ElementId] = new List<AdvisorBinding>();
                }
                advisorBindings[advisorBinding.ElementId].Add(advisorBinding);
            }
        }

        internal IEnumerable<IDependencyObjectAdvisor> GetAdvisors(string elementId)
        {
            if (!advisorBindings.ContainsKey(elementId)) return new IFrameworkElementAdvisor[0];
            var bindings = advisorBindings[elementId];
            return bindings.Select(binding => (IDependencyObjectAdvisor) advisors.GetExtension(binding.AdvisorType));
        }

        public void Start()
        {
            Elements.Manager = this;
        }

        public void Stop()
        {
            Elements.Manager = null;
        }
    }
}
